import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { withRouter } from 'react-router';
import { gql, useMutation, useQuery } from '@apollo/client';

import Button from '@kuiper-components/button';
import Table from '@knownsec/react-component/dist/Table';
import Pagination from '@knownsec/react-component/dist/Pagination';
import EmptyData from '../../../../components/empty/EmptyData';
import {
	getParams,
	searchStringParams,
} from '../../../../helpers/getUrlParams';
import HostSearchInput from '../../../../components/HostSearchInput';
import confirm from '../../../../components/confirm';
import Add from './Add';
import s from './Whitelist.module.css';

const REMOVE_GQL = gql`
	mutation ($ids: [String]!, $formSerializer: any) {
		explictKeywordWhitelistRemove(input: { ids: $ids })
			@rest(
				type: "ExplictKeywordWhitelistRemoveResponse"
				path: "/kb/delete_white_list_keywords"
				method: "POST"
				endpoint: "v2"
				bodySerializer: $formSerializer
				bodyKey: "input"
			) {
			code
			msg
		}
	}
`;

function queryGQLBuilder() {
	return gql`
		query ($word: String, $perPage: Int, $page: Int) {
			dataPagination: explictKeywordWhiteList(
				word: $word
				per_page: $perPage
				page: $page
			)
				@rest(
					type: "ExplictKeywordWhitelistResponse"
					path: "/kb/white_list_keywords?{args}"
					endpoint: "v2"
				) {
				pageInfo {
					currentPage
					hasNextPage
					hasPreviousPage
					itemCount
					pageCount
					perPage
				}
				items {
					_id
					word
				}
			}
		}
	`;
}

function Whitelist({ className, location, history }) {
	const params = getParams();
	const [type, setType] = React.useState('empty');
	const [total, setTotal] = React.useState(0);
	const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
	const [filter, setFilter] = React.useState(
		params || {
			word: '',
			page: 1,
			perPage: 10,
		}
	);
	const { data, loading, refetch } = useQuery(queryGQLBuilder(), {
		variables: filter,
	});
	const { tableData1 } = React.useMemo(() => {
		if (data?.dataPagination) {
			const tableData1 = data?.dataPagination?.items.map(item => {
				return { ...item, key: item._id };
			});
			const { itemCount } = data?.dataPagination?.pageInfo;
			setTotal(itemCount);
			return { tableData1 };
		} else {
			return { tableData1: [], pageSize: 10, page: 1 };
		}
	}, [data, filter]);
	const onSelectChange = newSelectedRowKeys => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};
	const handleSearch = word => {
		const search = searchStringParams({
			word: word,
			page: 1,
			perPage: 10,
		});
		setFilter({ word, page: 1, perPage: 10 });
		history.replace(`/policy-manage/keyword-settings/whitelist?${search}`);
	};

	const pageChange = (page, pageSize) => {
		const search = searchStringParams({
			word: filter.word,
			page: page,
			perPage: 10,
		});
		setFilter({ ...filter, page, perPage: pageSize });
		refetch({ ...filter, page, perPage: pageSize });
		history.replace(`/policy-manage/keyword-settings/whitelist?${search}`);
	};
	const [remove] = useMutation(REMOVE_GQL);
	const handleRemove = blacklistIds =>
		confirm.warning({
			message: '删除选中敏感词白名单，您确定要删除吗？',
			okText: '确定',
			cancelText: '取消',
			title: '提示',
			onOk: () =>
				remove({
					variables: {
						ids: blacklistIds,
					},
				}).then(() => {
					setSelectedRowKeys([]);
					pageChange(1, 10);
					refetch && refetch();
				}),
		});

	const columns = React.useMemo(
		() => [
			{
				title: '敏感词',
				dataIndex: 'word',
				key: 'word',
			},
			{
				title: '操作',
				dataIndex: '_id',
				key: '__actions__',
				className: s.action,
				width: 200,
				// eslint-disable-next-line react/display-name
				render: _id => {
					return (
						<div className={s.content}>
							<Button
								link
								primary
								className={s.btn}
								onClick={() => handleRemove([_id])}
							>
								删除
							</Button>
						</div>
					);
				},
			},
		],
		[]
	);
	React.useEffect(() => {
		if (!loading) setType('img')
	}, [loading])
	return (
		<div className={cn(className, s.whitelist)}>
			<div className={s.toolbox}>
				<Add refetch={refetch}>添加白名单</Add>
				<HostSearchInput
					placeholder="请输入敏感词"
					value={filter.word}
					onChange={handleSearch}
				/>
			</div>
			<Table
				pro
				loading={loading}
				columns={columns}
				data={tableData1}
				empty={<EmptyData type={type} className={s.nobor} />}
				rowSelection={rowSelection}
			/>
			<div className={cn('df aic jcsb mt5')}>
				<span
					className={selectedRowKeys.length ? s.batch : s.nobatch}
					onClick={() => handleRemove(selectedRowKeys)}
				>
					批量删除
				</span>
				{total > 10 && (
					<Pagination
						current={Number(filter?.page || 1)}
						pageSizeOptions={[10, 20, 50]}
						showSizeChanger
						showQuickJumper
						showTotal={total => `共${total}条`}
						total={total}
						onChange={pageChange}
					/>
				)}
			</div>
		</div>
	);
}

Whitelist.propTypes = {
	className: PropTypes.string,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
};

Whitelist.defaultProps = {
	className: s.url,
};

export default withRouter(Whitelist);
